package com.ubhave.powertracker;

import java.util.Calendar;
import java.util.Date;

import com.ubhave.powertracker.R;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

public class DailyQuestionnaireReminderNotification extends Service{

	SharedPreferences settings;
	SharedPreferences.Editor editor;
	LifeGuideConnector lgc;
	String usr;
	String intervention;
	
	PageSensorLogger psl;
	PageLogger pl;
	
	boolean inhibited;
	String[] inhibitedWeeks;
	int week;
	int day;
	int qday;
	Date currentDate;
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		
		return null;
	}
	
	@Override
    public void onCreate() {
		
		settings =PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		editor = settings.edit();
        lgc = new LifeGuideConnector(settings);
        usr = settings.getString("LifeGuideUser", "");
		intervention = settings.getString("LifeGuideInterventionId", "");
		
		if(settings.getBoolean("SensorsOn", false))
			psl = new PageSensorLogger(this);
			pl = new PageLogger(this);
		
		class AsyncLog extends AsyncTask{

			@Override
			protected Object doInBackground(Object... params) {
				//Usage Log
				try{
					/*editor.putString("usageLog", settings.getString("usageLog", "")+params[0].getClass().getSimpleName()+" "+new Date()+", ");
					editor.commit();
					if(!usr.equals("")&&!intervention.equals(""))
						lgc.postVar(intervention, usr, "user", "appUsageLog", settings.getString("usageLog", ""),settings.getString("authkey",""));
					else
						Log.i("POWeR Tracker: ", "Log fail usr: "+usr+" int: "+intervention);	
					*/
					pl.makeLog();
					//Sensor Log
					if(settings.getBoolean("SensorsOn", false)){
						psl.makeLog();
					}
				}
				catch(PowerTrackerInvalidAuthKeyException e){}
				return null;
			}
		};
		new AsyncLog().execute(this);
		
		inhibitCheck();
		
		if((!inhibited||!settings.getBoolean("QuestionnaireInhibitorOn", true))&&!usr.equals("")&&!intervention.equals("")){
			NotificationManager notificationManager = (NotificationManager) 
			getBaseContext().getSystemService(getBaseContext().NOTIFICATION_SERVICE);
			Notification notification = new Notification(R.drawable.star,
				"A new notification", System.currentTimeMillis());
			//System.currentTimeMillis()
			// Hide the notification after its selected
			notification.flags |= Notification.FLAG_AUTO_CANCEL;
			notification.defaults |= Notification.DEFAULT_SOUND;

			Intent intent = new Intent(getBaseContext(), QuestionnaireActivity.class);
			intent.putExtra("page", "1");
			intent.putExtra("name", "GoalEffort");
			intent.putExtra("orientation", "H");
			intent.putExtra("questionsPerPage", "3");
			intent.putExtra("type", "Likert");
			intent.putExtra("scale", "7");
			intent.putExtra("labelMode", "0");
			intent.putExtra("title", " ");
			intent.putExtra("multipart", "0");
			intent.putExtra("forGoal", "1");
			
			
			PendingIntent activity = PendingIntent.getActivity(getBaseContext(), 0, intent, 0);
			notification.setLatestEventInfo(getBaseContext(), "POWeR Tracker Reminder",
				"Its time to do your POWeR Tracker Daily Questionnaire", activity);
			notification.number += 1;
			notificationManager.notify(0, notification);
		}
			    
	    stopSelf();
	    
	}
	
	@Override
	public void onDestroy() {
        super.onDestroy();
        if(psl!=null)
        	psl.stopLocationSensing();
    }
       
	
	public void inhibitCheck(){
    	
    	//Detect if on inhibited week
		String[] startDateString = settings.getString("appStart", "").split("-");
		Date startDate = new Date(new Integer(startDateString[2]),new Integer(startDateString[1]),new Integer(startDateString[0]));
		currentDate = new Date();
		long diff = currentDate.getTime()-startDate.getTime();
		double daysDiff = diff/(1000*60*60*24);
		day = new Integer(new Double(daysDiff).intValue()+1);
		
		if(currentDate.getHours()<11)
			qday=day-1;
		else
			qday=day;
		
		week=new Double(Math.ceil(new Double(day/7.0))).intValue();
		
		
    	inhibited=false;
    	
    	if(settings.getBoolean("QDone-Daily-"+qday, false))
    			inhibited=true;
    	
        	
    }
	
	
		
}